package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * @program: project-market
 * @description: 字符串转换成数组的TypeHandler
 * @author: Weiwei Liu
 * @create: 2021-11-29 21:55
 **/
@Component // 注册
@MappedJdbcTypes(JdbcType.VARCHAR)  // 数据库中的类型
@MappedTypes(Integer[].class) // 转化后的数据类型
public class StringToIntegerArrayTypeHandler extends BaseTypeHandler<Integer[]> {

    ObjectMapper objectMapper = new ObjectMapper();

    private Class<Integer> clazz;

    public StringToIntegerArrayTypeHandler(Class<Integer> clazz) {
        this.clazz = clazz;
    }

    public StringToIntegerArrayTypeHandler() {
    }

    /**
     * Integer数组转换成[1,2,3]字符串
     *
     * @param preparedStatement JDBC预编译的参数
     * @param index             序号，为预编译sql语句提供占位符的序号
     * @param integers          需要被转换的Integer数组
     * @param jdbcType          被转换的jdbcType
     * @throws SQLException
     */
    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int index, Integer[] integers, JdbcType jdbcType) throws SQLException {

        String value = objectMapper.writeValueAsString(integers);

        preparedStatement.setString(index, value);
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {

        // 将[1,2,3]字符串转换成Integer数组
        return toArray(resultSet.getString(columnName));
    }

    @SneakyThrows
    private Integer[] toArray(String columnValue) {

        // 如果字段为空，转换成[]
        if (columnValue == null || columnValue.length() == 0) {
            return new Integer[0];
        }

        return objectMapper.readValue(columnValue, Integer[].class);
    }


    @Override
    public Integer[] getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return toArray(resultSet.getString(columnIndex));
    }

    @Override
    public Integer[] getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return toArray(callableStatement.getString(columnIndex));
    }
}
